<template>
  <a-modal
    v-model:visible="visible"
    @before-ok="handleOk"
    @cancel="handleCancel"
    @before-open="loadOptions"
  >
    <template #title>新增</template>
    <a-form ref="formRef" :model="formData" auto-label-width>
      <a-form-item
        field="userId"
        label="签到用户"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-select
          v-model="formData.userId"
          :options="userOptions"
          placeholder="请选择"
        />
      </a-form-item>
      <a-form-item
        field="signTime"
        label="签到时间"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-date-picker
          v-model="formData.signTime"
          placeholder="请输入"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { addUserSignUsingPost } from '@/service/backend/userSignController.ts';
import { Message } from '@arco-design/web-vue';
import { reactive, ref } from 'vue';
import { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
import useLoading from '@/hooks/useLoading';
import { listUserVoByPageUsingPost } from '@/service/backend/userController.ts';

const emit = defineEmits(['cancel', 'ok']);
const { loading, setLoading } = useLoading();
const visible = ref(false);
const formData = reactive<API.UserSignAddRequest>({
  userId: '',
  signTime: ''
});
const formRef = ref();
const userOptions = ref<SelectOptionData[]>();

/**
 * 加载option数据
 */
const loadOptions = async () => {
  await loadUserOption();
};

const loadUserOption = async () => {
  try {
    const { data, code } = await listUserVoByPageUsingPost({});
    if (code === 0 && data?.records) {
      // 构建 optionArray
      const optionArray = data.records.map(item => ({
        label: item.username, // 显示的名称
        //@ts-ignore
        value: item.id.toString() // 选项的值
      })) as SelectOptionData;
      userOptions.value = optionArray;
    }
  } catch (e: any) {
    Message.error(e.message);
  }
};

/**
 * @en-US Add node
 * @zh-CN 添加节点
 */
const handleAdd = async () => {
  if (loading.value) return;
  try {
    await addUserSignUsingPost(formData);
    Message.success('创建成功');
    return true;
  } catch (error: any) {
    Message.error(`创建失败,${error.message}`);
    return false;
  }
};

const open = () => {
  visible.value = true;
};

const handleOk = async done => {
  try {
    const error = await formRef.value.validate();
    if (!error) {
      await handleAdd(); // 提交数据
      done(true); // 关闭 Modal
      formRef.value?.resetFields();
      emit('ok');
    } else {
      done(false); // 阻止 Modal 关闭
    }
  } catch (e) {
    Message.error(e.message);
    done(false);
  }
};

function handleCancel() {
  formRef.value?.resetFields();
  emit('cancel');
}

defineExpose({
  open
});
</script>

<style scoped lang="less"></style>
